<script setup>
import { ref, reactive, onMounted } from 'vue';
import PostCard from './PostCard.vue';
import axios from "@/utils/axios.ts";

// 响应式状态
const selectedGame = ref(null);
const games = ref([]);
const posts = ref([]);
const isLoading = ref(false);
const hasMoreData = ref(true);
const page = ref(1);
const pageSize = ref(6);
const initialLoadChecked = ref(false);
const isRefreshing = ref(false); // 添加下拉刷新状态
const state = reactive({
  finished: false
});

// 初始化游戏列表
const initGames = async () => {
  try {
    const res = await axios.post("/api/home/getSixGames");
    if (res.code === 200) {
      games.value = res.data;
    }
  } catch (error) {
    console.error("获取游戏列表失败:", error);
  }
};

// 初始化帖子列表
const initPost = async () => {
  console.log("初始化帖子列表");
  page.value = 1;
  state.finished = false;
  isLoading.value = false;
  initialLoadChecked.value = false;
  
  // 手动设置isLoading为true，确保van-list状态同步
  isLoading.value = true;
  console.log("初始化时设置isLoading为true");
  
  try {
    await loadPosts();
  } catch (error) {
    console.error("初始化帖子列表失败:", error);
  } finally {
    // 确保在loadPosts完成后重置isLoading
    isLoading.value = false;
    console.log("初始化完成，重置isLoading为false");
  }
};

// 加载帖子数据

const loadPosts = async () => {

  try {
    const res = await axios.post("/api/home/pageQuery", {
      page: page.value,
      limit: pageSize.value,
    });
    console.log("ressss:", res);
    if (res.code == 200 && res.data) {
      // 处理返回的数据
      if (page.value === 1) {
        console.log("初始化帖子列表，数据量:", res.data.length);
        posts.value = res.data;
      } else {
        // 确保res.data是数组
        const newData = Array.isArray(res.data) ? res.data : [];
        console.log("追加帖子列表，数据量:", newData.length);
        posts.value.push(...newData);
      }

      // 判断是否还有更多数据
      if (res.data.length < pageSize.value) {
        state.finished = true;
        console.log("已加载全部数据，当前总数:", posts.value.length);
      } else {
        page.value++;
        console.log("准备加载下一页，新页码:", page.value);
      }
    } else {
      console.error("获取帖子列表失败:", res.message);
      // 请求失败时也标记为完成，避免无限加载
      state.finished = true;
    }
  } catch (error) {
    console.error("加载数据失败:", error);
    // 发生错误时也标记为完成，避免无限加载
    state.finished = true;
  }
  
  // 注意：不在loadPosts中修改isLoading状态，由onLoad函数负责
  console.log("loadPosts完成，finished:", state.finished, "posts数量:", posts.value.length);
};

// // 选择游戏
// const selectGame = (gameId) => {
//   selectedGame.value = gameId;
//   initPost();
// };

// 删除帖子
const handleRemovePost = (postId) => {
  posts.value = posts.value.filter(post => post.id !== postId);
};

// 加载更多数据
const onLoad = async () => {
  // 如果已完成，直接返回
  if (state.finished) {
    console.log("onLoad被阻止，因为已完成");
    return;
  }
  // 使用一个标记来防止重复加载
  if (isLoading.value) {
    console.log("检测到isLoading为true，忽略此次加载请求");
    return;
  }
  // 手动设置isLoading为true，确保状态同步
  isLoading.value = true;
  console.log("手动设置isLoading为true");
  
  try {
    await loadPosts();
  } catch (error) {
    console.error("onLoad过程中发生错误:", error);
  } finally {
    // 确保在loadPosts完成后重置isLoading
    isLoading.value = false;
    console.log("onLoad完成，重置isLoading为false");
  }
};

// 生命周期钩子
onMounted(() => {
  console.log("推荐页面初始化");
  initGames();//初始化游戏
  initPost();//初始化帖子

});

const onRefresh = async () => {
  console.log("触发下拉刷新");
  try {
    const res = await axios.post("/api/home/pageQuery", {
      page: 1,
      limit: 6,
    }).then(res => {
      if (res.code == 200 && res.data) {

          const newData = Array.isArray(res.data) ? res.data : [];
          console.log("追加帖子列表，数据量:", newData.length);
          posts.value=newData;

      }
    })

  } catch (error) {
    console.error("下拉刷新失败:", error);
  } finally {
    isRefreshing.value = false;
  }
};

</script>

<template>
  <div class="post-feed">
    <main class="main-content">
      <!-- 游戏展示区域 -->
      <div class="games-showcase">
        <div class="games-scroll-container">
          <!-- 全部选项 -->
          <div class="game-item"
               :class="{ active: selectedGame === null }"
               @click="selectGame(null)">
            <div class="game-icon">
              <div class="all-icon">全部</div>
            </div>
            <div class="game-name">全部</div>
          </div>

          <!-- 游戏列表 -->
          <div class="game-item"
               v-for="game in games"
               :key="game.id"
               :class="{ active: selectedGame === game.id }"
               @click="selectGame(game.gameId)">
            <div class="game-icon">
              <div class="all-icon">{{game.gameName}}</div>
              <!--              <img :src="game.image" :alt="game.name">-->
            </div>
            <div class="game-name">{{ game.gameName }}</div>
          </div>
        </div>
      </div>

      <!-- 帖子列表 -->
      <div class="posts-container">
        <van-pull-refresh
            v-model="isRefreshing"
            @refresh="onRefresh"
            success-text="刷新成功"
        >
        <van-list
            :loading="isLoading"
            :finished="state.finished"
            :immediate-check="false"
            finished-text="没有更多了"
            @load="onLoad"
            :offset="100"
        >
          <PostCard
              v-for="post in posts"
              :key="post.id"
              :post="post"
              @remove-post="handleRemovePost"
          />
        </van-list>
          </van-pull-refresh>
      </div>
    </main>
  </div>
</template>

<style scoped>
/* 基础样式 */
.post-feed {
  font-family: 'Inter', system-ui, sans-serif;
  background-color: #F9FAFB;
  color: #1F2937;
  min-height: calc(100vh - 50px); /* 减去底部导航栏的高度 */
  padding-bottom: 60px; /* 为底部导航栏留出空间 */
}

/* 页头样式 */
.header {
  padding: 1.5rem 1rem;
  background-color: white;
  border-bottom: 1px solid #F3F4F6;
}

@media (min-width: 640px) {
  .header {
    padding: 1.5rem 1.5rem;
  }
}

.header-container {
  max-width: 72rem;
  margin: 0 auto;
}

.page-title {
  font-size: 1.5rem;
  font-weight: 700;
  color: #111827;
  margin: 0;
}

@media (min-width: 640px) {
  .page-title {
    font-size: 1.875rem;
  }
}

/* 游戏推荐区域样式 */
.games-section {
  padding: 1rem 1rem 0.5rem;
  background-color: white;
  position: sticky;
  top: 56px; /* 与导航栏高度相同 */
  z-index: 50;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.games-container {
  display: flex;
  overflow-x: auto;
  gap: 1rem;
  padding-bottom: 1rem;
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
}

.games-container::-webkit-scrollbar {
  display: none; /* Chrome, Safari, Opera */
}

.game-card {
  flex: 0 0 auto;
  width: 75px; /* 原来的1/4宽度 */
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s;
}

.game-card:hover {
  transform: translateY(-4px);
}

.game-image {
  width: 100%;
  height: 75px; /* 正方形，与宽度相同 */
  overflow: hidden;
}

.game-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.game-name {
  padding: 0.25rem 0;
  font-size: 0.75rem;
  text-align: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: #333;
}

/* 游戏展示区域样式 */
.games-showcase {
  margin-bottom: 1.5rem;
  padding: 0 1rem;
}

.showcase-title {
  font-size: 1.125rem;
  font-weight: 600;
  margin-bottom: 1rem;
  color: #333;
}

.games-scroll-container {
  display: flex;
  overflow-x: auto;
  gap: 1rem;
  padding-bottom: 0.5rem;
  scrollbar-width: thin; /* Firefox */
  scrollbar-color: #888 #f1f1f1; /* Firefox */
}

.games-scroll-container::-webkit-scrollbar {
  height: 6px; /* Chrome, Safari, Edge */
}

.games-scroll-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 10px;
}

.games-scroll-container::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 10px;
}

.games-scroll-container::-webkit-scrollbar-thumb:hover {
  background: #555;
}

.game-item {
  flex: 0 0 auto;
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  transition: transform 0.2s;
}

.game-item:hover {
  transform: translateY(-4px);
}

.game-item.active {
  color: #1890ff;
}

.game-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  overflow: hidden;
  margin-bottom: 0.5rem;
  background-color: #f5f5f5;
  display: flex;
  justify-content: center;
  align-items: center;
}

.game-icon img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.all-icon {
  font-size: 0.875rem;
  font-weight: 500;
  color: #666;
}

.game-name {
  font-size: 0.75rem;
  text-align: center;
  white-space: nowrap;
  max-width: 70px;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 主内容区样式 */
.main-content {
  max-width: 72rem;
  margin: 0 auto;
  padding: 1.5rem 0;
}

@media (min-width: 640px) {
  .main-content {
    padding: 1.5rem 0;
  }
}

/* 帖子列表容器 */
.posts-container {
  display: flex;
  flex-direction: column;
  gap: 0;
}

/* 加载状态提示样式 */
.loading-indicator {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 0.5rem;
  padding: 1rem;
  color: #6B7280;
  margin-top: 1rem;
}

/* 没有更多数据提示样式 */
.no-more-data {
  padding: 2rem 1rem;
  color: #9CA3AF;
  font-size: 0.875rem;
  text-align: center;
  margin-top: 1rem;
  margin-bottom: 4rem; /* 为底部导航栏留出空间 */
}


</style>
